package com.fengwei.controller;

import cn.hutool.core.util.StrUtil;
import com.fengwei.util.EnumUtil;
import com.fengwei.util.PltResult;
import com.fengwei.util.ResponseUtil;
import com.fengwei.util.VerifyException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

@ControllerAdvice
@ResponseBody
public class ControllerExceptionHandler {
    private final static Logger logger = LoggerFactory.getLogger(ControllerExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    public Map<String, Object> errorHandler(Exception e) {
        try {
            if (e instanceof VerifyException) {
                VerifyException ve = ((VerifyException) e);
                String errCd = EnumUtil.getCode(((VerifyException) e).getErrorStatus());
                String errDsp = EnumUtil.getName(((VerifyException) e).getErrorStatus());
                //logger.error("VerifyError:" + errCd + "|" + errDsp);
                if (StrUtil.hasEmpty(ve.getErrorDesc())) {
                    return ResponseUtil.toJson(ve.errorStatus, null);
                } else {
                    return ResponseUtil.toJsonWithErrorDesc(ve.errorStatus, ve.getErrorDesc(), null);
                }
            } else if (e instanceof AccessDeniedException) {
                return ResponseUtil.toJson(PltResult.RESULT_CF987, null);
            } else {
                logger.error("Error:", e);
            }
        } catch (Exception e1) {
            logger.error("Error:", e1);
        }
        return ResponseUtil.toJson(PltResult.RESULT_CF999, null);
    }
}
